package com.wceManage.manage.util;

import com.wceManage.beans.SysMenu;
import com.wceManage.beans.SysRole;
import com.wceManage.beans.SysUser;
import com.wceManage.commons.util.CacheUtils;
import com.wceManage.commons.util.SpringContextHolder;
import com.wceManage.manage.security.SystemAuthorizingRealm.Principal;
import com.wceManage.services.SysMenuService;
import com.wceManage.services.SysRoleService;
import com.wceManage.services.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户工具类
 *
 * @author ThinkGem
 * @version 2013-12-05
 */
public class UserUtils {

    private static SysUserService userService = SpringContextHolder.getBean(SysUserService.class);
    private static SysRoleService roleService = SpringContextHolder.getBean(SysRoleService.class);
    private static SysMenuService resourceService = SpringContextHolder.getBean(SysMenuService.class);

    public static final String USER_CACHE = "userCache";
    public static final String USER_CACHE_ID_ = "id_";
    public static final String USER_CACHE_LOGIN_NAME_ = "ln";
//	public static final String USER_CACHE_LIST_BY_OFFICE_ID_ = "oid_";

    public static final String CACHE_ROLE_LIST = "roleList";
    public static final String CACHE_MENU_LIST = "menuList";
//	public static final String CACHE_AREA_LIST = "areaList";
//	public static final String CACHE_OFFICE_LIST = "officeList";
//	public static final String CACHE_OFFICE_ALL_LIST = "officeAllList";

    //七牛图片访问域名
    public static final String storeUrl = "http://qiniu.bieshuwang.com/";

    /**
     * 根据ID获取用户
     *
     * @param id
     * @return 取不到返回null
     */
    public static SysUser get(Long id) {
//		CacheUtils.remove(USER_CACHE, USER_CACHE_ID_ + id);
        SysUser user = (SysUser) CacheUtils.get(USER_CACHE, USER_CACHE_ID_ + id);
        if (user == null) {
            user = userService.queryById(id);
            if (user == null) {
                return null;
            }
            CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getUserId(), user);
            CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getAccount(), user);
        }
        return user;
    }

    /**
     * 清除当前用户缓存
     */
    public static void clearCache() {
        removeCache(CACHE_ROLE_LIST);
        removeCache(CACHE_MENU_LIST);
//		removeCache(CACHE_AREA_LIST);
//		removeCache(CACHE_OFFICE_LIST);
//		removeCache(CACHE_OFFICE_ALL_LIST);
        UserUtils.clearCache(getUser());
    }

    /**
     * 清除指定用户缓存
     *
     * @param user
     */
    public static void clearCache(SysUser user) {
        CacheUtils.remove(USER_CACHE, USER_CACHE_ID_ + user.getUserId());
        CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getAccount());
    }

    /**
     * 获取当前用户
     *
     * @return 取不到返回 new User()
     */
    public static SysUser getUser() {
        Principal principal = getPrincipal();
        if (principal != null) {
            SysUser user = get(principal.getId());
            if (user != null) {
                return user;
            }
            return new SysUser();
        }
        // 如果没有登录，则返回实例化空的User对象。
        return new SysUser();
    }

    /**
     * 获取当前用户角色列表
     *
     * @return
     */
    public static List<SysRole> getRoleList() {
        List<SysRole> roleList = (List<SysRole>) getCache(CACHE_ROLE_LIST);
        if (roleList == null) {
            SysUser user = getUser();
            if (user.isAdmin()) {
                roleList = roleService.findAllList(new SysRole());
            } else {
                SysRole role = new SysRole();
                roleList = roleService.queryList(role);
            }
            putCache(CACHE_ROLE_LIST, roleList);
        }
        return roleList;
    }

    /**
     * 获取当前用户授权菜单
     *
     * @return
     */
    public static List<SysMenu> getMenuList() {
//		removeCache(CACHE_MENU_LIST);
        List<SysMenu> menuList = (List<SysMenu>) getCache(CACHE_MENU_LIST);
        if (menuList == null) {
            SysUser user = getUser();
            if (user.isAdmin()) {//root
                menuList = resourceService.findAllList(new SysMenu());
            } else if ("2".equals(user.getUserRole())) {//admin
                menuList = resourceService.queryList(new SysMenu());
            } else {
                SysMenu m = new SysMenu();
                m.setUserId(user.getUserId());
                menuList = resourceService.findByUserId(m);
            }
            putCache(CACHE_MENU_LIST, menuList);
        }
        return menuList;
    }

    /**
     * 获取当前用户授权菜单(展示用)
     *
     * @return
     */
    public static List<SysMenu> getMenuListShow(Long roleId) {
//		removeCache(CACHE_MENU_LIST);
        List<SysMenu> menuList = new ArrayList<>();
        if (menuList.size() < 1) {
            SysMenu m = new SysMenu();
            m.setRoleId(roleId);
            menuList = resourceService.findByUserIdByShow(m);
//            putCache(CACHE_MENU_LIST, menuList);
        }
        return menuList;
    }

    /**
     * 获取子菜单
     *
     * @return
     */
    public static List<SysMenu> getSubMenuList(Long id) {
        @SuppressWarnings("unchecked")
        List<SysMenu> menuList = (List<SysMenu>) getCache(CACHE_MENU_LIST);
        if (menuList == null) {
            menuList = getMenuList();
            putCache(CACHE_MENU_LIST, menuList);
        }
        List<SysMenu> subMenuList = new ArrayList<SysMenu>();
        for (SysMenu menu : menuList) {
            if (menu.getParentId().longValue() == id.longValue()) {
                subMenuList.add(menu);
            }
        }
        return subMenuList;
    }

    /**
     * 获取授权主要对象
     */
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 获取当前登录者对象
     */
    public static Principal getPrincipal() {
        try {
            Subject subject = SecurityUtils.getSubject();
            Principal principal = (Principal) subject.getPrincipal();
            if (principal != null) {
                return principal;
            }
//			subject.logout();
        } catch (UnavailableSecurityManagerException e) {

        } catch (InvalidSessionException e) {

        }
        return null;
    }

    public static Session getSession() {
        try {
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession(false);
            if (session == null) {
                session = subject.getSession();
            }
            if (session != null) {
                return session;
            }
//			subject.logout();
        } catch (InvalidSessionException e) {

        }
        return null;
    }

    // ============== User Cache ==============

    public static Object getCache(String key) {
        return getCache(key, null);
    }

    public static Object getCache(String key, Object defaultValue) {
//		Object obj = getCacheMap().get(key);
        Object obj = getSession().getAttribute(key);
        return obj == null ? defaultValue : obj;
    }

    public static void putCache(String key, Object value) {
//		getCacheMap().put(key, value);
        getSession().setAttribute(key, value);
    }

    public static void removeCache(String key) {
//		getCacheMap().remove(key);
        getSession().removeAttribute(key);
    }

}
